package com.sea.base.ext.view

import android.graphics.Paint
import com.sea.base.ext.global.throwIfDebug
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

/**
 * TextView侧边加小icon的辅助方法
 * 返回TextView加的空格数和单行高度，方便代码设置
 *
 * @param spacePx 需要加空格的大小，如：icon.with
 * @return 空格数和单行文本高度（便于自行居中展示）
 */
@OptIn(ExperimentalContracts::class)
inline fun Paint.getSpannableSpace(spacePx: Int, resCallback: (spaces: String, textHeight: Int) -> Unit) {
    contract {
        callsInPlace(resCallback, InvocationKind.EXACTLY_ONCE)
    }

    val oneSpaceWidth = measureText("          ") / 10f
    var spaceCount = (spacePx / oneSpaceWidth + 0.5f).toInt()
    if (spaceCount > 10000) {
        spaceCount = 10000
        "传入的宽太大：$spacePx，oneSpaceWidth：$oneSpaceWidth".throwIfDebug()
    }
    val builder = StringBuilder()
    for (i in 0 until spaceCount) {
        builder.append(" ")
    }
    val fm = fontMetrics
    resCallback.invoke(builder.toString(), (fm.bottom - fm.top + 0.5f).toInt())
}